<template>
    <div class="search-bar">
        <icon class="s-icon" type="search" color="#9DA4B3" :size="16"></icon>
        <input class="s-input" @keydown="chooseCurrIndex($event)" @focus="searchFocus = true" @blur="searchFocus = false" type="text" placeholder="搜索" v-model="search">
        <el-scrollbar v-if="search && searchFocus" ref="searchBar" class="s-content" :native="false" :noresize="true" :style="{'display': (groupList && groupList.length > 0) || (friendList && friendList.length > 0) ? 'block' : 'none'}">
            <div class="s-list">
                <template v-if="friendList && friendList.length != 0">
                    <h4 class="s-list-title">好友</h4>
                    <div :class="['s-list-item',(type == 'friend' && currIndex == index)?'active':'']" :id="'search_'+item.id" v-for="(item,index) in friendList" :key="item.id" @mousedown="stopInputBlur($event)" @click="chooseFriend(item)">
                        <div class="avatar">
                            <img class="img" :src="item.usericon" alt="" v-if="item.usericon != ''">
                            <img class="img" src="../../assets/person_icon.jpg" alt="" v-else>
                        </div>
                        <div class="info" style="line-height: 15px;">
                            <!--exist remark-->
                            <template v-if="item.remark">
                                <template v-if="item.remark.toLocaleLowerCase().indexOf(search.toLocaleLowerCase()) != -1">
                                    <h4 class="nickname" v-html="highLight(item.remark)"></h4>
                                </template>
                                <template v-else>
                                    <div class="nickname" v-html="highLight(item.remark)"></div>
                                    <span class="nickname" style="font-size: 12px;color: #9DA4B3;">
                                        <span>昵称：</span>
                                        <span v-html="highLight(item.nickname)"></span>
                                    </span>
                                    <!--<h4 class="nickname" ></h4>-->
                                </template>
                            </template>
                            <!--no exist remark-->
                            <template v-else>
                                <h4 class="nickname" v-html="highLight(item.nickname)"></h4>
                            </template>

                        </div>
                    </div>
                </template>
                <template v-if="groupList && groupList.length != 0">
                    <h4 class="s-list-title">群聊</h4>
                    <div :class="['s-list-item',(type == 'group' && currIndex == index)?'active':'']" :id="'search_'+item.id" v-for="(item,index) in groupList" :key="item.id" @mousedown="stopInputBlur($event)" @click="chooseGroup(item)">
                        <div class="avatar">
                            <group-avatar v-lazy-container="{ selector: 'img' }" :id="item.id"></group-avatar>
                            <!--<img class="img" :src="item.group_icon" alt="" v-if="item.group_icon != ''">-->
                            <!--<img class="img" src="../../assets/group_icon.png" alt="" v-else>-->
                        </div>
                        <div class="info">
                            <h4 class="nickname" v-html="highLight(item.group_name)"></h4>
                        </div>
                    </div>
                </template>
            </div>
        </el-scrollbar>
    </div>
</template>
<script>
import { baseApi } from '@/api'
import icon from '@/components/icon/index'
import groupAvatar from '@/components/group-avatar/index'
import scrollIntoView from '@/utils/scroll-into-view'
export default {
    data() {
        return {
            searchFocus: false,
            type: 'friend',
            search: '',
            currIndex: 0
        }
    },
    components: {
        icon,
        groupAvatar
    },
    watch: {
        search(val) {
            if (val) {
                this.currIndex = 0
                this.$nextTick(() => {
                    if (this.friendList.length > 0) {
                        this.type = 'friend'
                    } else if (this.groupList.length > 0) {
                        this.type = 'group'
                    } else {
                        this.type = ''
                    }
                })
            }
        }
    },
    computed: {
        friendList() {
            let friendObj = this.$store.state.base.friendList
            let filterFriendList = null
            if (friendObj) {
                let friendList = []
                for (let key in friendObj) {
                    friendList = friendList.concat(friendObj[key])
                }
                if (this.search.trim() != '') {
                    filterFriendList = friendList.filter(el => {
                        return el.remark.toLocaleLowerCase().indexOf(this.search.toLocaleLowerCase()) != -1 || el.nickname.toLocaleLowerCase().indexOf(this.search.toLocaleLowerCase()) != -1
                    })
                } else {
                    filterFriendList = null
                }
            }
            return filterFriendList
        },
        groupList() {
            let groupList = this.$store.state.base.groupList
            let filterGroupList = null
            if (groupList) {
                if (this.search.trim() != '') {
                    filterGroupList = groupList.filter(el => { return el.group_name.toLocaleLowerCase().indexOf(this.search.toLocaleLowerCase()) != -1 })
                } else {
                    filterGroupList = null
                }
            }
            return filterGroupList
        }
    },
    methods: {
        chooseCurrIndex(event) {

            if (this.friendList.length == 0 && this.groupList.length == 0) {
                return
            }
            // down arrow key
            if (event.keyCode == 40) {
                let id = ''
                if (this.type == 'friend') {
                    if (this.currIndex < this.friendList.length - 1) {
                        this.currIndex = this.currIndex + 1
                        id = this.friendList[this.currIndex].id
                    } else if (this.currIndex == (this.friendList.length - 1) && this.groupList.length > 0) {
                        this.currIndex = 0
                        this.type = 'group'
                        id = this.groupList[0].id
                    }
                } else if (this.type == 'group') {
                    if (this.currIndex < this.groupList.length - 1) {
                        this.currIndex = this.currIndex + 1
                        id = this.groupList[this.currIndex].id
                    } else {
                        id = this.groupList[this.groupList.length -1].id
                    }
                }
                let target = document.getElementById('search_' + id)
                let container = document.querySelector('.s-list').parentNode.parentNode
                scrollIntoView(container, target)
                event.preventDefault()
            // up arrow key
            } else if (event.keyCode == 38) {
                let id = ''
                if (this.type == 'friend') {
                    if (this.currIndex > 0) {
                        this.currIndex = this.currIndex - 1
                        id = this.friendList[this.currIndex].id
                    } else {
                        id = this.friendList[0].id
                    }
                } else if (this.type == 'group') {
                    if (this.currIndex > 0) {
                        this.currIndex = this.currIndex - 1
                        id = this.groupList[this.currIndex].id
                    } else if (this.currIndex == 0 && this.friendList.length > 0) {
                        this.type = 'friend'
                        this.currIndex = this.friendList.length - 1
                        id = this.friendList[this.currIndex].id
                    }
                }
                let target = document.getElementById('search_' + id)
                let container = document.querySelector('.s-list').parentNode.parentNode
                scrollIntoView(container, target)
                event.preventDefault()
            } else if (event.keyCode == 13) {
                if (this.type == 'friend' && this.friendList.length > 0) {
                    let item = this.friendList[this.currIndex]
                    this.chooseFriend(item)
                } else if (this.type == 'group' && this.groupList.length > 0) {
                    let item = this.groupList[this.currIndex]
                    this.chooseGroup(item)
                }
                event.preventDefault()
            }
        },
        highLight(name) {
            if (this.search.trim()) {
                var reg = new RegExp(this.search.trim(), 'gi')
                name = name.replace(reg, function (txt) {
                    return '<span style="color: #4288FF;">' + txt + '</span>'
                })
            }
            return name
        },
        chooseFriend(item) {
            let params = {
                id: item.id,
                icon: item.usericon,
                name: item.remark !== '' ? item.remark : item.nickname,
                time: '',
                count: 0,
                msgType: 11,
                msgData: []
            }
            let inputObj = {
                content: '',
                atUserList: [],
                type: 'friend',
                id: item.id
            }
            this.$store.dispatch('insertChatInput', inputObj)
            this.$store.dispatch('createChat', params)
            this.search = ''
            this.$router.push({ path: '/message' })
        },
        stopInputBlur(e) {
            e.preventDefault()
        },
        chooseGroup(item) {
            baseApi.getGroupSubs({ group_id: item.id }).then(res => {
                if (res.code == 200) {
                    this.$store.dispatch('setCrrentGroupSubs', res.data)
                    let params = {
                        id: item.id,
                        icon: item.group_icon,
                        name: item.group_name,
                        time: '',
                        count: 0,
                        status: item.status,
                        msgType: 13,
                        msgData: []
                    }
                    let inputObj = {
                        content: '',
                        atUserList: [],
                        type: 'group',
                        id: item.id
                    }
                    this.$store.dispatch('insertChatInput', inputObj)
                    this.$store.dispatch('createChat', params)
                    this.search = ''
                    this.$router.push({ path: '/message' })
                } else {
                    // this.$socket.close()
                    this.$confirm('您的授权已失效，请重新登录！', '提示', {
                        confirmButtonText: '知道了',
                        showClose: false,
                        showCancelButton: false,
                        closeOnClickModal: false,
                        closeOnPressEscape: false,
                        type: 'warning'
                    }).then(() => {
                        sessionStorage.removeItem('key')
                        this.$store.dispatch('resetBase')
                        this.$store.dispatch('resetChat')
                        this.$router.push({ path: '/login' })
                        // window.location.href = window.location.protocol + '//' + window.location.host + '/login'
                    })
                }
            })
        }
    },
    updated() {
        if (this.$refs['searchBar']) {
            this.$refs['searchBar'].update()
        }
    }
}
</script>

<style lang="less" scoped>
.search-bar {
    position: relative;
    width: 244px;
    margin: 0 auto 6px;
    .s-icon {
        position: absolute;
        display: inline-block;
        vertical-align: middle;
        width: 30px;
        height: 30px;
        line-height: 30px;
        text-align: center;
        z-index: 101;
        top: 1px;
    }
    .s-input {
        width: 214px;
        height: 32px;
        line-height: 32px;
        border: 0;
        border-radius: 5px;
        background-color: #232A39;
        color: #fff;
        padding-left: 30px;
        font-size: 12px;
    }
    .s-content {
        position: absolute;
        z-index: 99;
        outline: none;
        background: #fff;
        width: 240px;
        height: 410px;
        top: 40px;
        left: 0;
        box-shadow: 0 0 10px #2a2a2a;
        border-radius: 2px;
        overflow: hidden;
        .s-list {
            .s-list-title {
                padding: 0 10px;
                height: 30px;
                line-height: 30px;
                color: #9DA4B3;
                background: #F4F4F4;
                font-size: 14px;
            }
            .s-list-item:focus {
                outline: none;
            }
            .s-list-item.active {
                background: #ccc;
            }
            .s-list-item {
                overflow: hidden;
                padding: 0 9px;
                display: flex;
                cursor: pointer;
                align-items: center;
                border-bottom: 1px solid #F4F4F4;
                height: 51px;
                .avatar {
                    float: left;
                    margin-right: 10px;
                    .img {
                        display: block;
                        width: 30px;
                        height: 30px;
                        border-radius: 2px;
                    }
                }
                .info {
                    overflow: hidden;
                    .nickname {
                        font-weight: 400;
                        font-size: 13px;
                        width: 100%;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                        word-wrap: normal;
                    }
                }
            }
        }
    }
}
</style>
